const app = getApp();
const util = require("../../../../../utils/util.js");
// index:当前展示第几组问题
// article_id_str：与当前问题相关联的所有问题
// step:进行到第几步
// article_id_str：跟当前问题相同的所有可能问题
var model_id, article_id_str, step, index,
    stepIndex = [], // 记录每一步的问题下标，用于返回时显示问题
    stepArticle = [], // 记录每一步的关联问题字符串，用户返回时请求数据
    questionData = [], // 当前测试的全部问题
    question, step_more;
let toggleCollection = true;
Page({
    data: {
        scroll: false,
    },
    onLoad: function(options) {
        // util.colleation(this, '', "1");
        toggleCollection = true;
        model_id = options.model_id;
        if (options.step_more != undefined) {
            step_more = parseInt(options.step_more)
        } else {
            step_more = 0;
        }
        this.getUrl().then(res => {
            this.init();
        }).catch(res => {
            this.init();
        });

    },
    getUrl() {
        return new Promise((resolve, reject) => {
            ks.request({
                url: app.globalData.api,
                success: function(res) {
                    if (res.statusCode >= 400) {
                        app.globalData.api = app.globalData.apibak;
                    }
                    return resolve(res);
                },
                fail: function(res) {
                    app.globalData.api = app.globalData.apibak;
                    return reject(res);
                },
            });
        });
    },
    init: function() {
        step = 1, index = 0, article_id_str = '';
        stepIndex[step] = index;
        stepArticle[step] = article_id_str;
        var _this = this;
        util.bstrequest('questionCount.php', { ac: 'query', model_id: model_id }, 'POST').then(res => {});
        ks.request({
            url: app.globalData.api,
            data: {
                action: 'questionlist',
                model_id: model_id,
                timestamp: new Date().getTime(),
            },
            method: "GET",
            header: { "content-type": "application/json" },
            success: res => {
                // 获取问题列表。
                questionData = res.data;
                _this.showQuestion()
            },
        });
    },
    // 展示问题方法
    showQuestion: function() {
        var _this = this;
        question = questionData[index]; // 当前问题
        try {
            var answerlist = question.value.split(','); // 分割当前问题
            _this.setData({
                step: step + step_more,
                question: question, // 当前问题属性
                answerlist: answerlist, // 问题列表，前端展示
            });

        } catch (e) {}
    },

    selectAnswer: function(e) {
        var _this = this;
        var attr_value = e.target.dataset.value;
        const $addClickNumber = {
            ac: "count",
            model_id: question.model_id,
            attr_id: question.id,
            answer: attr_value
        }
        util.bstrequest('questionCount.php', $addClickNumber, 'POST').then(res => {})
        ks.request({
            url: app.globalData.api,
            data: {
                action: 'answer',
                model_id: question.model_id,
                attr_id: question.id,
                attr_value: attr_value,
                article_id_str: article_id_str,
                timestamp: new Date().getTime(),
            },
            method: "GET",
            header: { "content-type": "application/json" },
            success: res => {
                // 如果当前的选项，没能匹配到后续的所有可能的问题
                if (res.data.article_id_str != undefined) {
                    // 点击当前问题时，请求该问题后续的所有问题，并在初始请求的问题列表中查找是否有对应的题目。
                    let found_question = false;
                    // 查找当前问题之后的问题
                    for (let i = index + 1; i < questionData.length; i++) {
                        // 循环请求结果中，当前数据的后续问题
                        for (let j = 0; j < res.data.attribute.length; j++) {
                            // 如果找到匹配的问题，结束循环
                            if (questionData[i].id == res.data.attribute[j].attribute_id) {
                                found_question = true;
                                break;
                            }
                        }
                        // 如果已经找到问题，结束循环，并将下一步的index置位对应问题的下标
                        if (found_question) {
                            index = i;
                            break;
                        }
                    }
                    if (found_question) {
                        article_id_str = res.data.article_id_str;
                        question = questionData[index];
                        step++;
                        stepIndex[step] = index;
                        stepArticle[step] = article_id_str;
                        _this.showQuestion();
                    } else {
                        _this.success(res.data.article_id_str);
                    }
                } else {
                    _this.failure();
                }
            },
        });
    },

    goback: function() {
        if (step == 1) {
            ks.navigateBack({
                delta: 1,
            })
        } else {
            step--;
            index = stepIndex[step]
            question = questionData[index];
            article_id_str = stepArticle[step];
            this.showQuestion();
        }
    },

    success: function(article_id) {
        ks.request({
                url: app.globalData.api,
                data: {
                    action: 'article',
                    article_id: article_id,
                    timestamp: new Date().getTime(),
                },
                method: "GET",
                header: { "content-type": "application/json" },
                success: res => {
                    var desc = res.data.desc;
                    var title = res.data.title;
                    //跳转模型
                    // desc不为空，不为null，并且能转换成纯数字，继续测试题目
                    if (desc != "" && desc != null && !isNaN(desc)) {
                        ks.redirectTo({
                                url: '/pages/tools/banshi/problem/item/item?model_id=' + desc + '&step_more=' + step,
                            })
                            //跳转文章  
                    } else if (desc.indexOf('http') > -1) {
                        ks.navigateTo({
                                url: '/pages/tools/banshi/problem/success/success?url=' + encodeURIComponent(desc) + '&title=' + title + '&model_id=' + model_id,
                            })
                            //跳转小程序
                    } else if (desc.indexOf('wx') == 0) {
                        ks.navigateToMiniProgram({
                                appId: desc,
                            })
                            //测试失败
                    } else if (!title) {
                        ks.navigateTo({
                            url: '/pages/tools/banshi/problem/failure/failure?desc=' + desc + '&model_id=' + model_id,
                        })
                    } else {
                        ks.navigateTo({
                            url: '/pages/tools/banshi/problem/success/success?model_id=' + model_id + '&desc=' + desc,
                        })
                    }
                }
            })
            // util.request(app.globalData.api, {
            //   action: 'article',
            //   article_id: article_id,
            //   timestamp: new Date().getTime(),
            // }).then(res => {
            //   var desc = res.data.desc;
            //   var title = res.data.title;
            //   //跳转模型
            //   // desc不为空，不为null，并且能转换成纯数字，继续测试题目
            //   if (desc != "" && desc != null && !isNaN(desc)) {
            //     wx.redirectTo({
            //       url: '/pages/problem/item/item?model_id=' + desc + '&step_more=' + step,
            //     })
            //     //跳转文章  
            //   } else if (desc.indexOf('http') > -1) {
            //     wx.navigateTo({
            //       url: '/pages/problem/success/success?url=' + encodeURIComponent(desc) + '&title=' + title + '&model_id=' + model_id,
            //     })
            //     //跳转小程序
            //   } else if (desc.indexOf('wx') == 0) {
            //     wx.navigateToMiniProgram({
            //       appId: desc,
            //     })
            //     //测试失败
            //   } else if (desc != "" && desc != null) {
            //     wx.navigateTo({
            //       url: '/pages/problem/failure/failure?desc=' + desc + '&model_id=' + model_id,
            //     })
            //   } else {
            //     wx.navigateTo({
            //       url: '/pages/problem/success/success?model_id=' + model_id,
            //     })
            //   }
            // });
    },

    failure: function() {
        ks.navigateTo({
            url: '/pages/tools/banshi/problem/failure/failure?model_id=' + model_id,
        })
    },
    onShareAppMessage: function() {
        return {
            path: `/pages/tools/banshi/problem/item/item?model_id=${model_id}`,
            imageUrl: app.globalData.shareImage ? app.globalData.shareImage : "http://imgbdb3.bendibao.com/xcxbdb/file/20212/9/20210209161843_68677.jpg",
            title: "本地宝"
        }
    },

    // 分享朋友圈
    onShareTimeline: function() {
        return {
            title: app.globalData.shareTitle ? app.globalData.shareTitle : "本地宝",
            imageUrl: app.globalData.shareImage ? app.globalData.shareImage : "http://imgbdb3.bendibao.com/xcxbdb/file/20212/9/20210209161843_68677.jpg",
            query: { model_id: model_id },
        }
    },

    onPageScroll() {
        if (toggleCollection) {
            this.setData({
                scroll: true,
            });
            toggleCollection = false;
        }

    },
    closeCollection() {
        toggleCollection = false;
    },
    openCollection() {
        toggleCollection = true;
    }
});